<?php
namespace app\index\controller;

use app\lib\exception\BaseException;
use EasyWeChat\Factory;
use app\common\model\User as UserModel;
use think\Controller;
use think\Request;

class Auth extends Controller
{
    public function getCode()
    {
        $request = Request::instance();
        cookie('last_url',$request->url(),60*10);
        $config = [
            'app_id' => config('ofcl.app_id'),
            'secret' => config('ofcl.app_secret'),
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
                'callback' => url('index/Auth/receiveCode'),
            ],
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        $oauth->redirect()->send();
    }

    public function receiveCode()
    {

        $config = [
            'app_id' => config('ofcl.app_id'),
            'secret' => config('ofcl.app_secret'),
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        $user_info = [
            'openid' => $user->getId(),  // 对应微信的 OPENID
            'nickname' => $user->getNickname(),// 对应微信的 nickname
            'headimgurl' => $user->getAvatar(), // 头像网址
        ];
        //查找用户把用户信息保存到session中，查不到新建
        $this->login($user_info);
        //跳转首页
        header('Location:'.cookie('last_url'));
    }

    public function login($user_info)
    {
        //查找用户，查不到新建
        $model = new UserModel();
        $user = $model->getByOpenId($user_info['openid']);
        if (!$user) {
            //创建用户
            $res = $model->createOne($user_info);
            $user = $model::getByOpenId($user_info['openid']);
            if(!$user) throw new BaseException();
        }
        $user = $user->toArray();
        session('user_info', $user);//把用户信息存入session
    }
}
